package fr.epsi.spring1.servletsWithSpring;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import fr.epsi.spring1.domain.User;
import fr.epsi.spring1.service.UserManager;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet2() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Logger.getRootLogger().debug("Login " + request.getParameter("login"));
		String login = request.getParameter("login");
		String password = request.getParameter("password");

		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserManager userManager = context.getBean(UserManager.class);
		
		User user = new User();
		user.setLogin(login);
		user.setPassword(password);
		if (userManager.isAutorized(user)) {
			Logger.getRootLogger().info("Login " + login + " is autorized");
			response.sendRedirect("hello.html");
		} else {
			Logger.getRootLogger().info("Login " + login + " is rejected");
			response.sendRedirect("index.html");
		}
	}

}
